package com.yc.study.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yc.study.entity.AnswerSheet;
import com.yc.study.entity.Topic;
import com.yc.study.mapper.AnswerSheetMapper;
import com.yc.study.service.IAnswerSheetService;
import com.yc.study.service.ITopicService;
import com.yc.study.vo.AnswerSheetVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 服务实现类
 *
 * @author 王妍
 * @since 2022-03-20
 */
@Service
public class AnswerSheetServiceImpl extends ServiceImpl<AnswerSheetMapper, AnswerSheet>
    implements IAnswerSheetService {

  @Autowired private ITopicService topicService;

  @Override
  @Transactional(rollbackFor = Exception.class)
  public Long save(Long id, List<AnswerSheetVo> answerSheetVos) {
    final List<AnswerSheet> collect =
        answerSheetVos.stream()
            .peek(answerSheetVo -> answerSheetVo.setStudentId(id))
            .map(
                answerSheetVo -> {
                  final AnswerSheet answerSheet = new AnswerSheet();
                  BeanUtils.copyProperties(answerSheetVo, answerSheet);
                  return answerSheet;
                })
            .collect(Collectors.toList());
    final List<Long> topicIdList =
        collect.stream().map(AnswerSheet::getTopicId).collect(Collectors.toList());
    // 保存结果
    saveBatch(collect);
    Map<Long, String> result = new HashMap<>();
    // 查询题目答案
    topicService
        .list(new LambdaQueryWrapper<Topic>().in(Topic::getId, topicIdList))
        .forEach(topic -> result.put(topic.getId(), topic.getRightAnswers()));
    return collect.stream()
        .filter(answerSheet -> result.get(answerSheet.getTopicId()).equals(answerSheet.getOption()))
        .count();
  }
}
